package com.wbj.sensor

import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.wbj.direction.sensor.compass.CompassView
import com.wbj.direction.sensor.direction.DirectionView
import com.wbj.sensor.service.OverlayService
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.widget.Toast


class MainActivity : AppCompatActivity() {

    private val compassView: CompassView by lazy { findViewById(R.id.compassView) }
    private val directionView: DirectionView by lazy { findViewById(R.id.directionView)}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(this@MainActivity)) {
                val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:$packageName"))
                startActivityForResult(intent, 10)
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if  (requestCode ==  10 ) {
            if  (Build.VERSION.SDK_INT >=  23 ) {
                if  (!Settings.canDrawOverlays( this )) {
                    // SYSTEM_ALERT_WINDOW permission not granted...
                    Toast.makeText(this , "not granted" ,Toast.LENGTH_SHORT);

                }else{
                    startService(Intent(this,OverlayService::class.java))
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        compassView.onResume()
        directionView.onResume()
    }

    override fun onPause() {
        super.onPause()
        compassView.onPause()
        directionView.onPause()
    }

    override fun onStop() {
        super.onStop()
        compassView.onStop()
        directionView.onStop()
    }
}